package com.zjcode.cas.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Request.Builder;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class OkHttpUtil {

    @Resource
    private OkHttpClient okHttpClient;

    /**
     * get
     *
     * @param url     请求的url
     * @param queries 请求的参数，在浏览器？后面的数据，没有可以传null
     * @return
     */
    public String get(String url, Map<String, String> queries) {
        String responseBody = "";
        StringBuffer sb = new StringBuffer(url);
        if (queries != null && queries
            .keySet()
            .size() > 0) {
            boolean firstFlag = true;
            Iterator iterator = queries
                .entrySet()
                .iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry<String, String>) iterator.next();
                if (firstFlag) {
                    sb.append("?" + entry.getKey() + "=" + entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
        Request request = new Builder()
            .url(sb.toString())
            .build();
        Response response = null;
        try {
            response = okHttpClient
                .newCall(request)
                .execute();
            int status = response.code();
            if (status == 200) {
                return response
                    .body()
                    .string();
            }
        } catch (Exception e) {
            log.error("okhttp put error >> ex = {}", ExceptionUtils.getStackTrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responseBody;
    }

    /**
     * 下载文件
     *
     * @param url
     * @param queries
     * @param header
     * @param targetDir
     * @return
     */
    public String downloadOctetStreamFile(String url,
                                          Map<String, String> queries,
                                          Map<String, Object> header,
                                          String targetDir) {
        // 文件下载后缀
        String suffix = UuidUtil.get32UUID();
        // 文件名称
        String fileName = "";

        StringBuffer sb = new StringBuffer(url);
        if (queries != null && queries
            .keySet()
            .size() > 0) {
            boolean firstFlag = true;
            Iterator iterator = queries
                .entrySet()
                .iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry<String, String>) iterator.next();
                if (firstFlag) {
                    sb.append("?" + entry.getKey() + "=" + entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
        // 放入header
        Builder httpBuilder = new Builder();
        httpBuilder.url(url);
        if (!Objects.isNull(header)) {
            header
                .entrySet()
                .stream()
                .forEach(each -> {
                    String key = each.getKey();
                    Object value = each.getValue();
                    httpBuilder.addHeader(key, String.valueOf(value));
                });
        }

        Request request = httpBuilder
            .url(sb.toString())
            .build();
        Response response = null;

        // 文件下载
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            response = okHttpClient
                .newCall(request)
                .execute();
            Headers headers = response.headers();
            // 获取出需要现在的名称
            String contentDisposition = headers.get("Content-Disposition");
            fileName = getFileName(contentDisposition);

            byte[] buf = new byte[4096];
            int len = 0;

            // 储存下载文件的目录
            String dirPath = targetDir + File.separator + suffix;
            File dir = new File(dirPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, fileName);
            is = response
                .body()
                .byteStream();
            fos = new FileOutputStream(file);
            int size = 0;
            long total = response
                .body()
                .contentLength();
            while ((size = is.read(buf)) != -1) {
                len += size;
                fos.write(buf, 0, size);
                // process为下载进度,目前不需要处理
                int process = (int) Math.floor(((double) len / total) * 100);
            }

            fos.flush();
            log.info("下载完成");

        } catch (Exception e) {
            log.error("okhttp put error >> ex = {}", ExceptionUtils.getStackTrace(e));
        } finally {
            if (response != null) {
                response.close();
            }

            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return suffix + File.separator + fileName;
    }

    private static String getFileName(String contentDisposition) {
        String fileName = contentDisposition;
        String[] split = fileName.split("=");
        fileName = split[1].replace("\"", "");
        try {
            fileName = URLDecoder.decode(fileName, "UTF-8");
            log.info(fileName);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return fileName;
    }


    /**
     * post
     *
     * @param url    请求的url
     * @param params post form 提交的参数
     * @return
     */
    public String post(String url, Map<String, String> params) {
        String responseBody = "";
        FormBody.Builder builder = new FormBody.Builder();
        //添加参数
        if (params != null && params
            .keySet()
            .size() > 0) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
        Request request = new Builder()
            .url(url)
            .post(builder.build())
            .build();
        Response response = null;
        try {
            response = okHttpClient
                .newCall(request)
                .execute();
            int status = response.code();
            if (status == 200) {
                return response
                    .body()
                    .string();
            }
        } catch (Exception e) {
            log.error("okhttp post error >> ex = {}", ExceptionUtils.getStackTrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responseBody;
    }

    public String post(String url, Map<String, String> body, Map<String, Object> header) {
        String responseBody = "";
        FormBody.Builder builder = new FormBody.Builder();
        //添加参数
        if (body != null && body
            .keySet()
            .size() > 0) {
            for (String key : body.keySet()) {
                builder.add(key, body.get(key));
            }
        }

        Builder httpBuilder = new Builder();
        httpBuilder.url(url);
        if (!Objects.isNull(header)) {
            header
                .entrySet()
                .stream()
                .forEach(each -> {
                    String key = each.getKey();
                    Object value = each.getValue();
                    httpBuilder.addHeader(key, String.valueOf(value));
                });
        }
        Request request = httpBuilder
            .post(builder.build())
            .build();

        Response response = null;
        try {
            response = okHttpClient
                .newCall(request)
                .execute();
            int status = response.code();
            if (status == 200) {
                return response
                    .body()
                    .string();
            }
        } catch (Exception e) {
            log.error("okhttp post error >> ex = {}", ExceptionUtils.getStackTrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responseBody;
    }

    public String post(String url, String json) {
        String responseBody = "";
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, json);

        Builder builder = new Builder();

        Request request = builder
            .url(url)
            .post(body)
            .build();

        Response response = null;
        try {
            response = okHttpClient
                .newCall(request)
                .execute();
            int status = response.code();
            if (status == 200) {
                return response
                    .body()
                    .string();
            }
        } catch (Exception e) {
            log.error("okhttp post error >> ex = {}", ExceptionUtils.getStackTrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responseBody;
    }

    public String post(String url, String json, Map<String, Object> header) {
        String responseBody = "";
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, json);

        //Builder builder = new Builder();
        //
        //Request request = builder
        //    .url(url)
        //    .post(body)
        //    .build();

        Builder httpBuilder = new Builder();
        httpBuilder.url(url);
        if (!Objects.isNull(header)) {
            header
                .entrySet()
                .stream()
                .forEach(each -> {
                    String key = each.getKey();
                    Object value = each.getValue();
                    httpBuilder.addHeader(key, String.valueOf(value));
                });
        }
        Request request = httpBuilder
            .post(body)
            .build();

        Response response = null;
        try {
            response = okHttpClient
                .newCall(request)
                .execute();
            int status = response.code();
            if (status == 200) {
                return response
                    .body()
                    .string();
            }
        } catch (Exception e) {
            log.error("okhttp post error >> ex = {}", ExceptionUtils.getStackTrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responseBody;
    }

    /**
     * post 上传文件
     *
     * @param url
     * @param params
     * @param fileType
     * @return
     */
    public String postFile(String url, Map<String, Object> params, String fileType) {
        String responseBody = "";
        MultipartBody.Builder builder = new MultipartBody.Builder();
        //添加参数
        if (params != null && params
            .keySet()
            .size() > 0) {
            for (String key : params.keySet()) {
                if (params.get(key) instanceof File) {
                    File file = (File) params.get(key);
                    builder.addFormDataPart(key,
                                            file.getName(),
                                            RequestBody.create(MediaType.parse(fileType), file));
                    continue;
                }
                builder.addFormDataPart(key,
                                        params
                                            .get(key)
                                            .toString());
            }
        }
        Request request = new Builder()
            .url(url)
            .post(builder.build())
            .build();
        Response response = null;
        try {
            response = okHttpClient
                .newCall(request)
                .execute();
            int status = response.code();
            if (status == 200) {
                return response
                    .body()
                    .string();
            }
        } catch (Exception e) {
            log.error("okhttp postFile error >> ex = {}", ExceptionUtils.getStackTrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responseBody;
    }
}
